<?php
                                                                                                                                                                                                                                                                                                                                        
// TTTTTTTTTTTTTTTTTTTTTTT                  MMMMMMMM               MMMMMMMM                                CCCCCCCCCCCCMMMMMMMM               MMMMMMMM  SSSSSSSSSSSSSSS 
// T:::::::::::::::::::::T                  M:::::::M             M:::::::M                             CCC::::::::::::M:::::::M             M:::::::MSS:::::::::::::::S
// T:::::::::::::::::::::T                  M::::::::M           M::::::::M                           CC:::::::::::::::M::::::::M           M::::::::S:::::SSSSSS::::::S
// T:::::TT:::::::TT:::::T                  M:::::::::M         M:::::::::M                          C:::::CCCCCCCC::::M:::::::::M         M:::::::::S:::::S     SSSSSSS
// TTTTTT  T:::::T  TTTTTppppp   ppppppppp  M::::::::::M       M::::::::::M   eeeeeeeeeeee          C:::::C       CCCCCM::::::::::M       M::::::::::S:::::S            
//         T:::::T       p::::ppp:::::::::p M:::::::::::M     M:::::::::::M ee::::::::::::ee       C:::::C             M:::::::::::M     M:::::::::::S:::::S            
//         T:::::T       p:::::::::::::::::pM:::::::M::::M   M::::M:::::::Me::::::eeeee:::::ee     C:::::C             M:::::::M::::M   M::::M:::::::MS::::SSSS         
//         T:::::T       pp::::::ppppp::::::M::::::M M::::M M::::M M::::::e::::::e     e:::::e     C:::::C             M::::::M M::::M M::::M M::::::M SS::::::SSSSS    
//         T:::::T        p:::::p     p:::::M::::::M  M::::M::::M  M::::::e:::::::eeeee::::::e     C:::::C             M::::::M  M::::M::::M  M::::::M   SSS::::::::SS  
//         T:::::T        p:::::p     p:::::M::::::M   M:::::::M   M::::::e:::::::::::::::::e      C:::::C             M::::::M   M:::::::M   M::::::M      SSSSSS::::S 
//         T:::::T        p:::::p     p:::::M::::::M    M:::::M    M::::::e::::::eeeeeeeeeee       C:::::C             M::::::M    M:::::M    M::::::M           S:::::S
//         T:::::T        p:::::p    p::::::M::::::M     MMMMM     M::::::e:::::::e                 C:::::C       CCCCCM::::::M     MMMMM     M::::::M           S:::::S
//       TT:::::::TT      p:::::ppppp:::::::M::::::M               M::::::e::::::::e                 C:::::CCCCCCCC::::M::::::M               M::::::SSSSSSS     S:::::S
//       T:::::::::T      p::::::::::::::::pM::::::M               M::::::Me::::::::eeeeeeee          CC:::::::::::::::M::::::M               M::::::S::::::SSSSSS:::::S
//       T:::::::::T      p::::::::::::::pp M::::::M               M::::::M ee:::::::::::::e            CCC::::::::::::M::::::M               M::::::S:::::::::::::::SS 
//       TTTTTTTTTTT      p::::::pppppppp   MMMMMMMM               MMMMMMMM   eeeeeeeeeeeeee               CCCCCCCCCCCCMMMMMMMM               MMMMMMMMSSSSSSSSSSSSSSS   
//                        p:::::p                                                                                                                                       
//                        p:::::p                                                                                                                                       
//                       p:::::::p                                                                                                                                      
//                       p:::::::p                                                                                                                                      
//                       p:::::::p                                                                                                                                      
//                       ppppppppp                                                                                                                                      
                                                                                                                                                                     
//  _____      __  __         ____ __  __ ____  
// |_   __ __ |  \/  | ___   / ___|  \/  / ___|     | AUTHOR: Xiaohe
//   | || '_ \| |\/| |/ _ \ | |   | |\/| \___ \     | EMAIL: 496631085@qq.com
//   | || |_) | |  | |  __/ | |___| |  | |___) |    | WECHAT: he4966
//   |_|| .__/|_|  |_|\___|  \____|_|  |_|____/     | DATETIME: 2021/07/3
//      |_|                                         | TpMeCMS

namespace app\api\controller;
use app\common\controller\Api;
use think\Db;
use EasyWeChat\Factory;
use think\Config;
use fast\Random;
/**
 * 公共无需登陆接口
 * @ApiInternal()
 */
class Tpmecmscom extends Api
{

    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

  
    /**
     * 可在继承app\common\controller\Tpmecms 下面的里面直接使用该控制器里面的方法 使用方法：$this->p_tpmecsm();
     *
     * @return void
     */
    protected function p_tpmecms()
    {
        $this->success('TpMeCms', ['com' => 'TpMeCMS']);
    }

    protected function re_image($str)
    {
        return str_replace("/attachment/image","/",$str);
    }

    
    /**
     * 获取房源信息
     *
     * @param int $goods_id 房源id
     * @return void
     */
    protected function GetGoodsData($goods_id){
        $data = Db::name('goods')->find($goods_id);
        if(!$data){
            $this->error('没有该房源');
        }

        $data['tags'] = Db::name('tag')->where('id','in',$data['tag_ids'])->column('title');
        $data['type_list'] = Db::name('typeimages')->where('goods_id',$goods_id)->select(); 
        //该房源附近学校
        // $nearby_school = $this->GetNearbySchool($goods_id);

        // $data['nearby_school'] = $nearby_school;

        // $data['goodscate_name'] = Db::name('goodscate')->where('id',$data['goodscate_id'])->value('cate_name');
        // $data['postcode_name'] = Db::name('postcode')->where('id',$data['postcode_id'])->value('name');

        // $room = Db::name('room')->where('goods_id',$goods_id)->select();
        // $data['room'] = $room;

        return $data;
    }



    /**
     * 获取房源信息2
     *
     * @param int $goods_id 房源id
     * @return void
     */
    protected function GetGoodsData2($goods_id){
        $data = Db::name('goods')->find($goods_id);
        if(!$data){
            return null;
            // $this->error('没有该房源');
        }

        $data['tags'] = Db::name('tag')->where('id','in',$data['tag_ids'])->column('title');
        $data['type_list'] = Db::name('typeimages')->where('goods_id',$goods_id)->select(); 
        //该房源附近学校
        // $nearby_school = $this->GetNearbySchool($goods_id);

        // $data['nearby_school'] = $nearby_school;

        // $data['goodscate_name'] = Db::name('goodscate')->where('id',$data['goodscate_id'])->value('cate_name');
        // $data['postcode_name'] = Db::name('postcode')->where('id',$data['postcode_id'])->value('name');

        // $room = Db::name('room')->where('goods_id',$goods_id)->select();
        // $data['room'] = $room;

        return $data;
    }



    /**
     * 获取房源信息数组
     *
     * @param int $goods_ids 房源id
     * @return void
     */
    protected function GetGoodsIdsData($goods_ids=null){

        if(!$goods_ids){
            return null;
        }
        $list = Db::name('goods')->where('id','in',$goods_ids)->select();
        // halt($list);

        // if(strstr(',',$goods_ids)){

        
            foreach ($list as $key => &$data) {
                $data['tags'] = Db::name('tag')->where('id','in',$data['tag_ids'])->column('title');
                $data['type_list'] = Db::name('typeimages')->where('goods_id',$data['id'])->select(); 
            }
        // }else{
        //     $list['tags'] = Db::name('tag')->where('id','in',$list['tag_ids'])->column('title');
        //     $list['type_list'] = Db::name('typeimages')->where('goods_id',$list['id'])->select();
        // }



        return $list;
    }


    /**
     * 获取某个房源附近学校
     *
     * @return void
     */
    protected function GetNearbySchool($goods_id){
        $nearby_school = Db::name('nearby_school')->where('goods_id',$goods_id)->select();
        if($nearby_school){
            //获取学校信息
            $schools = $this->GetAllSchool();
            foreach($nearby_school as &$val){
                if(isset($schools[$val['school_id']]))
                $val['school'] = $schools[$val['school_id']];
            }
        }
        return $nearby_school;
    }

    /**
     * 获取订单信息
     *
     * @param int $id 订单id
     * @return void
     */
    protected function GetOrderData($id)
    {
        $res = Db::name('order')->find($id);
        if($res){
            $res['googs'] = $this->GetGoodsData($res['goods_id']);
            // $res['json'] = json_decode(htmlspecialchars_decode($res['json']),true);
            $res['date'] = date('Y-m-d H:i',$res['time']);
            $res['pay_data'] =['pay_ps'=>Config::get('site.pay_ps'),'pay_image'=>Config::get('site.pay_image')];
        }
        
        return $res;
    }

    /**
     * 获取微信接收消息的用户openid
     *
     * @return void
     */
    protected function GetWeiXinMsgOpenids()
    {
        $ids = Config::get('site.wx_msg_ids');
        $wx_openids = Db::name('user')->where('id','in',$ids)->column('wx_openid');
        // foreach($wx_openids as $key =>$val){
        //     if(strlen($val)<10){
        //         // halt($val);
        //         unset($wx_openids[$key]);
        //     }
        // }

        foreach($wx_openids as $key =>$val){
            if(strlen($val)<10){
                unset($wx_openids[$key]);
            }
        }
        return $wx_openids;
    }

    /**
     * 获取全部学校
     *
     * @return array
     */
    protected function GetAllSchool(){
        return Db::name('school')->column('*','id');
    }

    /**
     * 增加房源资讯好
     * @return void
     */
    protected function IncArtGood($id,$uid){
        Db::name('art')->where('id',$id)->setInc('good');
    }

    /**
     * 增加房源资讯不好
     * @return void
     */
    protected function IncArtNoGood($id,$uid){
        Db::name('art')->where('id',$id)->setInc('no_good');
    }


    /**
     * 增加房源资讯好
     * @return void
     */
    protected function DecArtGood($id,$uid){
        Db::name('art')->where('id',$id)->setDec('good');
    }

    /**
     * 增加房源资讯不好
     * @return void
     */
    protected function DecArtNoGood($id,$uid){
        Db::name('art')->where('id',$id)->setDec('no_good');
    }

    /**
     * 获取文章点赞信息
     *
     * @param int $id 文章id
     * @param int $uid 用户id
     * @return void
     */
    protected function GetGoodData($id,$uid){
        return Db::name('good')->where('id',$id)->where('uid',$uid)->find();
    }



    /**
     * 增加房源资讯浏览
     *
     * @return void
     */
    protected function AddArtView($id){
        Db::name('art')->where('id',$id)->setInc('view');
    }


    /**
     * 添加客户
     *
     * @return int
     */
    protected function AddClients($data){
        $id = Db::name('clients')->where('tel',$data['tel'])->value('id');
        if($id)return $id;

        $data['time'] = time();
        return Db::name('clients')->insertGetId($data);
    }

    /**
     * 获取客户
     *
     * @return int
     */
    protected function GetClients($id){
       
        return  Db::name('clients')->where('id',$id)->find();
    }


    /**
     * 获取客户需求
     *
     * @return int
     */
    protected function GetClientsNeed($id){
       
        $res = Db::name('clients_need')->where('id',$id)->find();
        if(!$res){
            $this->error('没有该需求');
        }
        $res['clients'] = $this->GetClients($res['clients_id']);
        return $res;
    }



    /**
     * 增加房源浏览记录
     *
     * @return void
     */
    protected function AddGoodsLookLog($goods_id,$uid){
        if($uid){
            Db::name('goods_look_log')->where(['goods_id'=>$goods_id,'uid'=>$uid])->delete();
            Db::name('goods_look_log')->insert(['goods_id'=>$goods_id,'uid'=>$uid]);
        }
        
    }


    /**
     * 删除房源浏览记录
     *
     * @return void
     */
    protected function DelGoodsLookLog($id,$uid){
        if($uid){
            return Db::name('goods_look_log')->where('id',$id)->where('uid',$uid)->delete();
        }
        
    }

    
    /**
     * 删除客户
     *
     * @return void
     */
    protected function DelClients($id){
        if($id>0){
            
            return Db::name('clients')->where('id',$id)->delete();
        }else{
            return false;
        }
        
    }
    

    /**
     * 获取活动信息
     *
     * @param int $id 活动id
     * @return void
     */
    protected function GetActData($id){
        return Db::name('activity')->where('id',$id)->find();
    }


    /**
     * 居室id转数组
     *
     * @return void
     */
    protected function GoodscateIdsToArray($ids){
        $goodscate = Db::name('goodscate')->column('cate_name','id');
        $arr = array();

        if(!is_array($ids)){
            $ids = explode(',',$ids);
        }


        foreach($ids as $id){
            if(isset($goodscate[$id]))
            $arr[] = $goodscate[$id];
        }

        return $arr;
       
    }

    /**
     * 房源ids转数组
     *
     * @return void
     */
    protected function GoodsIdsToArray($ids){
        $list = Db::name('goods')->where('id','in',$ids)->select();



        foreach($list as $key=>&$data){
    
            $data['tags'] = Db::name('tag')->where('id','in',$data['tag_ids'])->column('title');
            $data['type_list'] = Db::name('typeimages')->where('goods_id',$data['id'])->select(); 
        }

        return $list;
       
    }


    /**
     * tag_ids转数组
     *
     * @return void
     */
    protected function TagIdsToArray($ids){
        $tags = Db::name('tag')->where('id','in',$ids)->column('title');
        return $tags;


        $arr = array();

        if(!is_array($ids)){
            $ids = explode(',',$ids);
        }


        foreach($ids as $id){
            if(isset($tags[$id]))
            $arr[] = $tags[$id];
        }

        return $arr;
       
    }

    /**
     * 获取用户的pid
     *
     * @return void
     */
    protected function GetUserPid($uid)
    {
        return Db::name('user')->where('id',$uid)->value('pid');
    }



    /**
     * 获取用户的提成上级pid
     *
     * @return void
     */
    protected function GetUserCommissionPid($uid)
    {
        $pid = Db::name('user')->where('id',$uid)->value('pid');
        if($pid){
            $user = $this->GetLtdUserData($this->auth->id);
            if(isset($user['com'])){
                return $pid;//$user['com'];
            }
        }

        return null;
        
    }

    /**
     * 获取公司用户信息
     *
     * @param int $uid 用户id
     * @return void
     */
    protected function GetLtdUserData($uid){
        $user = Db::name('user')->find($this->auth->id);
        if($user){
            $user['ltder'] = Db::name('ltder')->where('uid',$this->auth->id)->find();
            return $user;
        }
        return null;
    }


    /**
     * 添加管理员用户账号
     * @ApiInternal()
     * @param int $uid
     * @return void
     */
    public function add_admin_user($uid)
    {
        //查询公司信息
        $ltd = Db::name('ltd')->where('uid',$uid)->find();

        $params['user_id'] = $uid;
        $res = Db::name('admin')->where('user_id',$uid)->find();
        if(!$res){

       
            $params['username'] = $ltd['tel'];
            $params['nickname'] = $ltd['ltd_name'];
            $params['salt'] = Random::alnum();
            $params['password'] = md5(md5($ltd['tel']) . $params['salt']);
            $params['avatar'] = '/assets/img/avatar.png'; //设置新管理员默认头像。
            $params['status'] = 'normal';
        

            $id = Db::name('admin')->insertGetId($params);
            Db::name('ltd')->where('id',$ltd['id'])->update(['admin_id'=>$id]);
            Db::name('auth_group_access')->insert(['uid'=>$id,'group_id'=>3]);
        }
    }

    /**
     * 添加用户为主管
     * @ApiInternal()
     * @param int $uid 用户id
     * @param int $admin_id 管理id
     * @return void
     */
    public function add_user_zg($uid)
    {
        $this->add_admin_user($uid);

        $ltd = Db::name('ltd')->where('uid',$uid)->find();
        $ltder = Db::name('ltder')->where('uid',$uid)->find();
        if($ltder){
            $this->error('已存在该用户');
        }
        $data['name'] = $ltd['name'];
        // $data['wechat'] = $this->request->param('wechat','');
        // $data['email'] = $this->request->param('email','');
        // $data['ps'] = $this->request->param('ps','');   
        $data['tel'] = $ltd['tel'];
        $data['uid'] = $uid;

        $data['ltd_id'] = $ltd['id'];
        $data['admin_id'] = $this->GetAdminIdByLtdId($data['ltd_id']);//

        $data['role_status'] = '1';   //角色:1=主管,2=员工,3=兼职人员
        
        $data['time'] = time();
        $data['status_switch'] = 1;

        $res = Db::name('ltder')->insert($data);

    }


 
    /**
     * 更新房源坐标
     * @ApiInternal()
     * @param int $ids id
     * @return void
     */
    public function update_goods_geo($ids=null)
    {
        $res = Db::name('goods')->find($ids);
        if($res['lng'] && $res['lat'] ){
            $geo = new \addons\redisgeo\controller\Index;
            $geo->add_geo($res['lng'] , $res['lat'] ,$res['id']);
        }
    }


    /**
     * 获取提成的💰的数据
     * @ApiInternal()
     * @param int $ids id
     * @return void
     */
    public function GetCommissionMoneyData($uid)
    {
        // halt($uid);
        $data['total'] = $this->GetCommissionTotal($uid);//总
        $data['out'] = $this->GetCommissionOut($uid);
        $data['money'] = $data['total'] - $data['out'];
        // halt($data);
        return $data;
    }

    /**
     * 获取提成总金额
     * @ApiInternal()
     * @param int $pid
     * @return void
     */
    public function GetCommissionTotal($pid)
    {
    
        $data['pid'] = $pid;
        $res = Db::name('commission')
            ->where($data)
            ->sum('commission');
        return $res;
    }

    /**
     * 获取提成总数量
     * @ApiInternal()
     * @param int $pid
     * @return void
     */
    public function GetCommissionNum($pid)
    {
    
        $data['pid'] = $pid;
        $res = Db::name('commission')
            ->where($data)
            ->count();
        return $res;
    }

    /**
     * 获取提现总金额
     * @ApiInternal()
     * @param int $pid
     * @return void
     */
    public function GetCommissionOut($uid)
    {
    
        $data['uid'] = $uid;
        $data['status'] = '2';
        $res = Db::name('out')
            ->where($data)
            ->sum('money');
        return $res;
    }



    // /**
    //  * 添加提成按比例
    //  * @ApiInternal()
    //  * @param int $id
    //  * @return void
    //  */
    // public function AddCommissionlog($id)
    // {
    //     // com_ratio1
    //     $clients_need = $this->GetClientsNeed($id);

    //     $ltder = Db::name('ltder')->where('uid',$clients_need['pid'])->find();

    //     $ltd = Db::name('ltd')->where('id',$ltder['ltd_id'])->find();
      
    //     $commission1 = $clients_need['commission'] * $ltd['com_ratio1'];


    //     // halt($clients_need);
    //     if($commission1 > 0)
    //     $this->AddCommission($clients_need['pid'], $clients_need['id'],$commission1 ,'提成一级');


    //     //查找这个人的上级
    //     $pid = Db::name('user')->where('id',$clients_need['pid'])->value('pid');
    //     if($pid){        
    //         $commission2 = $clients_need['commission'] * $ltd['com_ratio2'];
    //         if($commission2 > 0)
    //         $this->AddCommission($pid, $clients_need['id'],$commission2 ,'提成二级');
    //     }

    //     // $data['uid'] = $uid;
    //     // $data['status'] = '2';
    //     // $res = Db::name('out')
    //     //     ->where($data)
    //     //     ->count('money');
    //     // return $res;
    // }




    /**
     * 添加提成金额
     * @ApiInternal()
     * @param int $id
     * @return void
     */
    public function AddCommissionlog($id)
    {
        // com_ratio1
        $clients_need = $this->GetClientsNeed($id);

        $ltder = Db::name('ltder')->where('uid',$clients_need['pid'])->find();

        $ltd = Db::name('ltd')->where('id',$ltder['ltd_id'])->find();
      
        $commission1 = $clients_need['commission']; //* $ltd['com_ratio1'];


        // halt($clients_need);
        if($commission1 > 0)
        $this->AddCommission($clients_need['pid'], $clients_need['id'],$commission1 ,'提成一级');


        //查找这个人的上级
        $pid = Db::name('user')->where('id',$clients_need['pid'])->value('pid');
        if($pid){        
            $commission2 = $clients_need['commission2'] ;//* $ltd['com_ratio2'];
            if($commission2 > 0)
            $this->AddCommission($pid, $clients_need['id'],$commission2 ,'提成二级');
        }

        // $data['uid'] = $uid;
        // $data['status'] = '2';
        // $res = Db::name('out')
        //     ->where($data)
        //     ->count('money');
        // return $res;
    }

    /**
     * 添加提成
     * 
     * @ApiInternal()
     * @param [type] $pid
     * @param [type] $order_id
     * @param [type] $commission
     * @param [type] $ps
     * @return void
     */
    public function AddCommission($pid,$order_id,$commission,$ps=null)
    {
        $data['pid'] = $pid;
        $data['order_id'] = $order_id;
        $res = Db::name('commission')->where($data)->find();
        if(!$res){
            $data['time'] = time();
            $data['commission'] = $commission;
            $data['ps'] = $ps;
            $data['id'] = Db::name('commission')->insertGetId($data);
        }
    }
    


    /**
     * 更具公司id获取admin_id
     * @ApiInternal()
     * @param int $ltd_id 公司id
     * @return void
     */
    public function GetAdminIdByLtdId($ltd_id)
    {
        $ltd = DB::name('ltd')->find($ltd_id);
        if(!$ltd){
            $this->error('没有该公司',$ltd_id);
        }
        if(empty($ltd['admin_id'])){
            $this->error('该公司还没有绑定后台');
        }
        return $ltd['admin_id'];
    }
    

    //模版消息——————————————————————————————————————————


    /**
     * 获取微信公众号
     * @ApiWeigh (997)
     * @ApiInternal()
     * @return void
     */
    protected function get_wx_gzh_app()
    {
         $config = [
             'app_id' => Config('site.wx_app_id'),//,
             'secret' => Config('site.wx_secret'),//,
         
             // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
             'response_type' => 'array',
         
             //...
         ];
         
         $app = Factory::officialAccount($config);

         return $app;
    }


    /**
     * 发送公众号模板消息给用户
     * @ApiInternal()
     * @param string $wx_openid 微信公众号openid
     * @param string $keyword1 自定义
     * @param string $keyword2 自定义
     * @param string $path
     * @return void
     */
    public function send_template_message_user($wx_openid='ooB8g6Hu3fa5P0oeMSpURFPVZRS4',$keyword1,$keyword2,$path='/pages/u_xjdS/u_xjdS')
    {
        
        $app = $this->get_wx_gzh_app();    
        $data = $app->template_message->send([
            'touser' => $wx_openid,//微信公众号openid,
            'template_id' => '_es-MdHZUO-voldjdevPADHj28JQ_t9bPzxowh_M8LM',//模板消息id
            'url' => 'https://he4966.cn/',//模板消息跳转地址
            'miniprogram' => [              //模板消息跳转小程序。小程序比网址优先级高，也可以注释其一
                    'appid' => Config('site.app_id'),
                    'pagepath' => $path,
            ],
            'data' => [
                'first' =>['您好，您有新的订单信息，请及时查看','#173177'],
                'keyword1' =>[$keyword1,'#173177'],//订单编号
                'keyword2' =>[$keyword2,'#173177'],//订单时间
                // 'keyword3' =>[$service,'#173177'],
                'remark' =>['请尽快登入小程序查看','#173177'],

            ],
        ]);
        return $data;
    }




    //模版消息——————————————————————————————————————————



    /**
     * 更新微信公众号wx_openid
     * @ApiInternal()
     * @return void
     */
    public function update_wx_openid()
    {
        $app = $this->get_wx_gzh_app();
        $next_openid = null;//'oYBUWs3A4KD6kfvfBXXcJOor9-Tw';
        $ci = 0;
        // halt($users);
        // $t= true;
     
            $users = $app->user->list($next_openid);
            // if($users['total']<130 || empty($users)){$t =false;}
            // $next_openid = $users['next_openid'];
        // halt($users);
            foreach($users['data']['openid'] as $key=>$openId){
                $wx_data = Db::name('user')->where('wx_openid',$openId)->find();
                unset($up_data);
                if(!$wx_data){//没有微信公众号的opengid  才去执行

                    $user = $app->user->get($openId);
                    // print_r($users);
                    // halt($user);
                    // if(!empty($user['openid']) && !empty($user['unionid'])){
                        $up_data['wx_openid'] = $user['openid'];//微信openid
                        $up_data['nickname'] = $user['nickname'];//微信nickname
                        $up_data['headurl']  = $user['headimgurl'];//微信headimgurl
                        $t_user = Db::name('user')->where('unionid',$user['unionid'])->find();
                        if($t_user){
                            // halt($t_user);

                            $res = Db::name('user')->where('unionid',$user['unionid'])->update($up_data);
                            if($res){
                                $ci++;
                            }

                        }
                        
                        unset($up_data);
                        
                    // }
                    unset($user);
                }else{
                    $user = $app->user->get($openId);
                    
                    $up_data['nickname'] = $user['nickname'];//微信nickname
                    $up_data['avatar']  = $user['headimgurl'];//微信headimgurl
                    $up_data['updatetime']  = time();
                    Db::name('user')->where('wx_openid',$openId)->update($up_data);
                }
                
            }
      
        echo $ci;
        file_put_contents('./gz_all.txt',$users['total']);
        // halt($users);
    }
    

// TTTTTTTTTTTTTTTTTTTTTTT                  MMMMMMMM               MMMMMMMM                                CCCCCCCCCCCCMMMMMMMM               MMMMMMMM  SSSSSSSSSSSSSSS 
// T:::::::::::::::::::::T                  M:::::::M             M:::::::M                             CCC::::::::::::M:::::::M             M:::::::MSS:::::::::::::::S
// T:::::::::::::::::::::T                  M::::::::M           M::::::::M                           CC:::::::::::::::M::::::::M           M::::::::S:::::SSSSSS::::::S
// T:::::TT:::::::TT:::::T                  M:::::::::M         M:::::::::M                          C:::::CCCCCCCC::::M:::::::::M         M:::::::::S:::::S     SSSSSSS
// TTTTTT  T:::::T  TTTTTppppp   ppppppppp  M::::::::::M       M::::::::::M   eeeeeeeeeeee          C:::::C       CCCCCM::::::::::M       M::::::::::S:::::S            
//         T:::::T       p::::ppp:::::::::p M:::::::::::M     M:::::::::::M ee::::::::::::ee       C:::::C             M:::::::::::M     M:::::::::::S:::::S            
//         T:::::T       p:::::::::::::::::pM:::::::M::::M   M::::M:::::::Me::::::eeeee:::::ee     C:::::C             M:::::::M::::M   M::::M:::::::MS::::SSSS         
//         T:::::T       pp::::::ppppp::::::M::::::M M::::M M::::M M::::::e::::::e     e:::::e     C:::::C             M::::::M M::::M M::::M M::::::M SS::::::SSSSS    
//         T:::::T        p:::::p     p:::::M::::::M  M::::M::::M  M::::::e:::::::eeeee::::::e     C:::::C             M::::::M  M::::M::::M  M::::::M   SSS::::::::SS  
//         T:::::T        p:::::p     p:::::M::::::M   M:::::::M   M::::::e:::::::::::::::::e      C:::::C             M::::::M   M:::::::M   M::::::M      SSSSSS::::S 
//         T:::::T        p:::::p     p:::::M::::::M    M:::::M    M::::::e::::::eeeeeeeeeee       C:::::C             M::::::M    M:::::M    M::::::M           S:::::S
//         T:::::T        p:::::p    p::::::M::::::M     MMMMM     M::::::e:::::::e                 C:::::C       CCCCCM::::::M     MMMMM     M::::::M           S:::::S
//       TT:::::::TT      p:::::ppppp:::::::M::::::M               M::::::e::::::::e                 C:::::CCCCCCCC::::M::::::M               M::::::SSSSSSS     S:::::S
//       T:::::::::T      p::::::::::::::::pM::::::M               M::::::Me::::::::eeeeeeee          CC:::::::::::::::M::::::M               M::::::S::::::SSSSSS:::::S
//       T:::::::::T      p::::::::::::::pp M::::::M               M::::::M ee:::::::::::::e            CCC::::::::::::M::::::M               M::::::S:::::::::::::::SS 
//       TTTTTTTTTTT      p::::::pppppppp   MMMMMMMM               MMMMMMMM   eeeeeeeeeeeeee               CCCCCCCCCCCCMMMMMMMM               MMMMMMMMSSSSSSSSSSSSSSS   
//                        p:::::p                                                                                                                                       
//                        p:::::p                                                                                                                                       
//                       p:::::::p                                                                                                                                      
//                       p:::::::p                                                                                                                                      
//                       p:::::::p                                                                                                                                      
//                       ppppppppp                                                                                                                                      



    /**
     * 获取一级用户id
     *
     * @param int $uid 用户id
     * @ApiInternal()
     * @return array
     */
    public function GetOneLevelUid($uid)
    {
        // halt($uid);
        return Db::name('user')->where('pid',$uid)->column('id');
    }

    /**
     * 公司人员获取一代直推
     *
     * @param int $uid 用户id
     * @return array
     */
    protected function LtderGetOneLevelUid($uid){
        $users = $this->GetOneLevelUid($uid);
        if($users){
            // $users = Db::name('ltder')->where('uid','in',$users)->column('uid');//公司人员
            return $users;
        }
        return null;
    }


    /**
     * 公司人员获取二代uid
     *
     * @param int $uid 用户id
     * @return array
     */
    protected function LtderGetTwoLevelUid($uid){


        $users_one = $this->LtderGetOneLevelUid($uid);
        
        $two_users = array();
        if($users_one){
            foreach ($users_one as $key => $uid1) {
                $temp = $this->LtderGetOneLevelUid($uid1);
                if($temp){//如果有人  合并
                   $two_users = array_merge($two_users,$temp);
                }//

            }           
        }
        return $two_users;
    }


    /**
     * 公司人员获取一二代uid
     *
     * @param int $uid 用户id
     * @return array
     */
    protected function LtderGetOneTwoLevelUid($uid){


        $users_one = $this->LtderGetOneLevelUid($uid);
        
        $two_users = array();
        if($users_one){
            foreach ($users_one as $key => $uid1) {
                $temp = $this->LtderGetOneLevelUid($uid1);
                if($temp){//如果有人  合并
                   $two_users = array_merge($two_users,$temp);
                }//

            }           
        }

        return array_merge($users_one,$two_users);
    }







    /**
     * 兑换到微信余额（微信提现）
     *
     * @param string $openid 微信openid
     * @param float $money 提现的金额（分）
     * @param string $out_order
     * @param string $desc
     * @return void
     */
    protected function ExchangeToWechatBalance($openid,$money,$out_order,$desc='提现说明',$bug=false)
    {
        
        $data = [
            'partner_trade_no' => $out_order, // 商户订单号，需保持唯一性(只能是字母或者数字，不能包含有符号)
            'openid' => $openid,    //微信openid
            'check_name' => 'NO_CHECK', // NO_CHECK：不校验真实姓名, FORCE_CHECK：强校验真实姓名
            // 're_user_name' => '小小亦', // 如果 check_name 设置为FORCE_CHECK，则必填用户真实姓名
            'amount' => $money, // 企业付款金额，单位为分
            'desc' => $desc // 企业付款操作说明信息。必填
        ];
  
        if($bug)halt($data);//调试输出数据

        $app = $this->get_pay_app();
    
        $transferData =  $app->transfer->toBalance($data);
        // ["return_code"] => string(7) "SUCCESS"
        // ["return_msg"] => string(7) "NO_AUTH"
        // ["mch_appid"] => string(18) "wx58af440837882842"
        // ["mchid"] => string(10) "1504804021"
        // ["result_code"] => string(4) "FAIL"
        // ["err_code"] => string(7) "NO_AUTH"
        // ["err_code_des"] => string(73) "产品权限验证失败,请查看您当前是否具有该产品的权限"


        
        if($transferData['result_code']!="SUCCESS"){
            $this->error($transferData["err_code_des"]);
        }
        

        $res_tx = $app->transfer->queryBalanceOrder($out_order);

    //    ["return_code"] => string(7) "SUCCESS"
    //    ["result_code"] => string(7) "SUCCESS"
    //    ["partner_trade_no"] => string(11) "test1111111"
    //    ["mch_id"] => string(10) "1517607021"
    //    ["detail_id"] => string(32) "10101030720692010077892911054996"
    //    ["status"] => string(7) "SUCCESS"
    //    ["reason"] => NULL
    //    ["openid"] => string(28) "oP0Js5VQP8KZpcp7hPZlcbHCyefk"
    //    ["transfer_name"] => NULL
    //    ["payment_amount"] => string(3) "100"
    //    ["transfer_time"] => string(19) "2020-10-07 22:49:16"
    //    ["payment_time"] => string(19) "2020-10-07 22:49:16"
    //    ["desc"] => string(13) "提现1.00元"
    //    ["appid"] => string(18) "wx0fc161ddec2fa1f9"

        

    //    ["return_code"] => string(7) "SUCCESS"
    //    ["result_code"] => string(7) "SUCCESS"
    //    ["partner_trade_no"] => string(18) "TS2020101498514910"
    //    ["mch_id"] => string(10) "1517607021"
    //    ["detail_id"] => string(32) "10101030720692010148279901732996"
    //    ["status"] => string(7) "SUCCESS"
    //    ["reason"] => NULL
    //    ["openid"] => string(28) "oP0Js5X1I-cNvdKcUUoRhua2icKs"
    //    ["transfer_name"] => NULL
    //    ["payment_amount"] => string(3) "100"
    //    ["transfer_time"] => string(19) "2020-10-14 11:04:04"
    //    ["payment_time"] => string(19) "2020-10-14 11:04:04"
    //    ["desc"] => string(32) "店铺提现1.00元，手续费0"
    //    ["appid"] => string(18) "wx0fc161ddec2fa1f9"

        if($res_tx['return_code']=='SUCCESS' && $res_tx['result_code']=='SUCCESS' &&$res_tx['status']=='SUCCESS'){//判断如果支付成功

            return true;
        }else{
            return $this->error('提现未成功',$res_tx);
        }
    } 

}
